package com.sakura.system.utils;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.sakura.system.entity.gld.User;
import com.sakura.system.exception.BusinessErrorException;
import com.sakura.system.service.impl.gldimpl.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * gld
 * 2024-3-4
 * 拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private UserServiceImpl service;

//    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Objects handler){
        // 从 请求中获取token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)){
            // 如果请求头没拿到,到请求参数中拿一下试一试.
            token = request.getParameter("token");
        }
        // 开始token验证
        if (StrUtil.isBlank(token)){
            throw new BusinessErrorException("无效token,请重新登陆!");
        }
//        获取token中的id
        String userId;
        User user;
        try {
            userId = JWT.decode(token).getAudience().get(0);
//            根据id查询数据库
            user = service.fibdByById(Integer.valueOf(userId));
        } catch (Exception e){
            String errMsg = "token验证失败,请重新登陆!";
            log.info(errMsg+",token="+token, e);
            throw new BusinessErrorException(errMsg);
        }

        if (user == null){
            throw new BusinessErrorException("用户不存在,请先注册.");
        }
        try {
            // 用户密码加签 验证 token
            JWTVerifier build = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            build.verify(token);
        } catch (JWTVerificationException e){
            throw new BusinessErrorException("token验证失败,请重新登陆!");
        }


        return true;

    }



}
